package com.stylefeng.web.wx.service.impl;

import javax.annotation.PostConstruct;

import com.stylefeng.web.wx.WxConfigProperties;
import com.stylefeng.web.wx.handler.LogHandler;
import com.stylefeng.web.wx.handler.MsgHandler;
import com.stylefeng.web.wx.handler.SubscribeHandler;
import me.chanjar.weixin.mp.constant.WxMpEventConstants;
import org.apache.ibatis.ognl.NullHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;



import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.kefu.result.WxMpKfOnlineList;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;

/**
 * 
 * @author Binary Wang
 *
 */
@Service
public class WeixinService extends WxMpServiceImpl {
  private final Logger logger = LoggerFactory.getLogger(this.getClass());

  @Autowired
  protected LogHandler logHandler;








  @Autowired
  private MsgHandler msgHandler;


  @Autowired
  private SubscribeHandler subscribeHandler;

  private WxMpMessageRouter router;

  @PostConstruct
  public void init() {
    final WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
    config.setAppId(WxConfigProperties.appid);// 设置微信公众号的appid
    config.setSecret(WxConfigProperties.appsecret);// 设置微信公众号的app corpSecret
    config.setToken(WxConfigProperties.token);// 设置微信公众号的token
    config.setAesKey(WxConfigProperties.aeskey);// 设置消息加解密密钥
    super.setWxMpConfigStorage(config);

  }



  public WxMpXmlOutMessage route(WxMpXmlMessage message) {
    try {
      return this.router.route(message);
    } catch (Exception e) {
      this.logger.error(e.getMessage(), e);
    }

    return null;
  }

  public boolean hasKefuOnline() {
    try {
      WxMpKfOnlineList kfOnlineList = this.getKefuService().kfOnlineList();
      return kfOnlineList != null && kfOnlineList.getKfOnlineList().size() > 0;
    } catch (Exception e) {
      this.logger.error("获取客服在线状态异常: " + e.getMessage(), e);
    }

    return false;
  }


}
